package org.springblade.modules.admin.service.approve;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.modules.admin.entity.*;
import org.springblade.modules.admin.enums.ApproveStatusEnum;
import org.springblade.modules.admin.service.BuildingService;
import org.springblade.modules.admin.service.IBuildingContactsService;
import org.springblade.modules.admin.service.IBuildingExtService;
import org.springblade.modules.admin.service.IBusinessWorkService;
import org.springblade.modules.admin.service.approve.strategy.ApproveBusinessFlow;
import org.springblade.modules.admin.vo.BuildingVO;
import org.springblade.modules.admin.vo.BusinessApproveVO;
import org.springblade.modules.admin.vo.approve.BuildingSubmitVO;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.TransactionStatus;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description 项目勘误流程
 * @Author ysq
 * @Date 2021/12/7
 **/
public class BuildingFlow implements ApproveBusinessFlow {

	private final BuildingService buildingService = SpringUtil.getBean(BuildingService.class);

	private final IBusinessWorkService businessWorkService = SpringUtil.getBean(IBusinessWorkService.class);

	private final IBuildingContactsService buildingContactsService = SpringUtil.getBean(IBuildingContactsService.class);

	private final IBuildingExtService buildingExtService = SpringUtil.getBean(IBuildingExtService.class);

	@Override
	public Object detail(Long businessApproveId) {
		BusinessApprove businessApprove = businessApproveService.getById(businessApproveId);
		if (businessApprove == null) {
			throw new ServiceException("审批流程不存在！");
		}
		//项目数据
		BuildingVO buildingData = buildingService.selectBuilding(businessApprove.getWorkOrderId());
		if (Func.isNotEmpty(buildingData)) {
			BuildingExt buildingExt = buildingService.selectBuildingExtDetail(buildingData.getId());
			buildingData.setBuildingExt(buildingExt);
		}
		//提交数据
		BuildingSubmitVO submitData = null;
		BusinessWork businessWork = businessWorkService.getById(businessApprove.getBusinessWorkId());
		if (businessWork != null) {
			submitData = JSONUtil.toBean(businessWork.getUpdateData(),BuildingSubmitVO.class);
		}
		Map<String, Object> map = new HashMap<>(2);
		map.put("buildingData",buildingData);
		map.put("submitData",submitData);
		return map;
	}

	@Override
	public boolean approve(BusinessApproveVO businessApprove) {
		BusinessApprove approve = businessApproveService.getById(businessApprove.getId());
		if (approve == null) {
			throw new ServiceException("审批流程不存在！");
		}
		if (approve.getApproveStatus() != ApproveStatusEnum.PENDING.getId()) {
			throw new ServiceException("流程已审批，不能重复审批！");
		}

		BladeUser bladeUser = AuthUtil.getUser();
		approve.setApproveIds(String.valueOf(bladeUser.getUserId()));
		approve.setApproveName(bladeUser.getUserName());
		approve.setRemark(businessApprove.getRemark());
		approve.setApproveStatus(businessApprove.getApproveStatus());

		// 手动开启事务
		TransactionStatus transactionStatus = platformTransactionManager.getTransaction(transactionDefinition);
		try {
			if (businessApproveService.updateById(approve)) {
				// 处理审批通过业务逻辑
				if (approve.getApproveStatus() == ApproveStatusEnum.PASSED.getId()){
					// 更新楼盘信息表
					BuildingSubmitVO submitData = JSONUtil.toBean(businessApprove.getSubmitData(),BuildingSubmitVO.class);
					Building building = buildingService.getById(approve.getWorkOrderId());
					if (building == null || submitData == null) {
						throw new ServiceException("未找到对应工单!");
					}
					// 定位修改标识
					boolean addressFlushFlag = Func.isNotEmpty(submitData.getLatitude()) ||  Func.isNotEmpty(submitData.getLongitude());
					BeanUtils.copyProperties(submitData,building);
					buildingService.updateById(building);
					if (addressFlushFlag) {
						buildingService.addRedisBuilding();
					}

					// 更新小区联系人表
					BuildingContacts buildingContacts = buildingContactsService.getOne(Wrappers.<BuildingContacts>lambdaQuery().eq(BuildingContacts :: getBuildingId, building.getId()),false);
					if (buildingContacts == null) {
						buildingContacts = new BuildingContacts();
						buildingContacts.setBuildingId(building.getId());
					}
					BeanUtils.copyProperties(submitData,buildingContacts);
					buildingContactsService.saveOrUpdate(buildingContacts);

					// 更新项目扩展信息
					if (Func.isNotEmpty(submitData.getBuildingExt())) {
						BuildingExt buildingExt = buildingExtService.getOne(Wrappers.<BuildingExt>lambdaQuery().eq(BuildingExt :: getBuildingId, approve.getWorkOrderId()), false);
						if (buildingExt == null) {
							buildingExt = new BuildingExt();
							buildingExt.setBuildingId(building.getId());
						}
						BeanUtils.copyProperties(submitData.getBuildingExt(),buildingExt, "id");
						buildingExtService.saveOrUpdate(buildingExt);

						// 更新别名
						if (Func.isNotEmpty(buildingExt.getRelationAliases())) {
							Building newBuilding = buildingService.getById(approve.getWorkOrderId());
							buildingService.addRelationAliases(buildingExt.getRelationAliases(), newBuilding);
						}
					}
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
			platformTransactionManager.rollback(transactionStatus);
			throw new ServiceException("审批失败: " + e.getMessage());
		}

		platformTransactionManager.commit(transactionStatus);
		return true;
	}

}
